package org.mcjug.locationmailer.service;

import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import oauth.signpost.OAuth;

import org.mcjug.locationmailer.R;
import org.mcjug.locationmailer.model.Email;
import org.mcjug.locationmailer.oauth.xauth.XoauthAuthenticator;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.sun.mail.smtp.SMTPTransport;

public class GmailService extends Service {
	public static final String EMAIL_INTENT_EXTRA = "email";
	public static final String EMAIL_NOTIFICATION_INTENT_ACTION = "emailNotification";
	public static final String EMAIL_SUCCESS = "org.mcjug.locationmailer.EmailSuccess";
	public static final String EMAIL_MSG = "org.mcjug.locationmailer.EmailMessage";
	
	public static final String RECEIVE_EMAIL_NOTIFICATIONS = 
		"org.mcjug.locationmailer.RECEIVE_EMAIL_NOTIFICATIONS";
	
	public static final String SEND_EMAIL_NOTIFICATIONS = 
		"org.mcjug.locationmailer.SEND_EMAIL_NOTIFICATIONS";
  
	public int onStartCommand(Intent intent, int flags, int startId) {
		Email email = intent.getParcelableExtra(EMAIL_INTENT_EXTRA);
		sendEmail(email);

		return START_NOT_STICKY;
	}

	private void sendEmail(Email email) {
		Intent intent = new Intent(EMAIL_NOTIFICATION_INTENT_ACTION);
		try {
			SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(getApplicationContext());		
			String oauthToken = prefs.getString(OAuth.OAUTH_TOKEN, null);
			String oauthTokenSecret = prefs.getString(OAuth.OAUTH_TOKEN_SECRET, null);
			
			if (TextUtils.isEmpty(oauthToken) || TextUtils.isEmpty(oauthTokenSecret)) {
				intent.putExtra(EMAIL_SUCCESS, false);
				intent.putExtra(EMAIL_MSG, getString(R.string.msgGmailOAuthNoTokens));
				return;
			}
			
			SMTPTransport smtpTransport = XoauthAuthenticator.connectToSmtp(
					"smtp.googlemail.com", 587, email.getSender(), oauthToken,
					oauthTokenSecret, XoauthAuthenticator.getAnonymousConsumer(), true);
			
			Properties props = System.getProperties();
			props.put("mail.smtps.host", "smtp.gmail.com");
			props.put("mail.smtps.auth", "true");			
			Session session = Session.getInstance(props, null);
			
			List<String> recipients = email.getRecipients();
			for (String recipient: recipients) {
				Message msg = new MimeMessage(session);
				msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
				msg.setFrom(new InternetAddress(email.getSender()));
				msg.setSubject(email.getSubject());
				msg.setText(email.getBody());
				msg.setHeader("X-Mailer", "Android program");
				msg.setSentDate(new Date());
				//smtpTransport.sendMessage(msg, msg.getAllRecipients());
			}
			
			intent.putExtra(EMAIL_SUCCESS, true);
		} catch (Exception e) {
			intent.putExtra(EMAIL_SUCCESS, false);
			String msg = (e.getMessage() == null ? e.toString() : e.getMessage());
			intent.putExtra(EMAIL_MSG, String.format(getString(R.string.msgEmailError), msg));
		} finally {
			sendBroadcast(intent, RECEIVE_EMAIL_NOTIFICATIONS);
		}
	}

	public IBinder onBind(Intent arg0) {
		return null;
	}
}
